<template>
  <div class="user-dashboard">
    <!-- 欢迎信息 -->
    <div class="welcome-section">
      <el-card class="welcome-card">
        <div class="welcome-content">
          <div class="user-info">
            <el-avatar :size="60" :src="userInfo?.imageurl">
              <span>{{ userInfo?.username?.charAt(0) || 'U' }}</span>
            </el-avatar>
            <div class="user-details">
              <h3>欢迎回来，{{ userInfo?.username || '用户' }}！</h3>
              <p>账号：{{ userInfo?.account }}</p>
            </div>
          </div>
          <div class="quick-actions">
            <el-button type="primary" @click="$router.push('/user/transfer')">
              <el-icon><Money /></el-icon>
              转账汇款
            </el-button>
            <el-button @click="$router.push('/user/account')">
              <el-icon><User /></el-icon>
              个人信息
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 账户概览 -->
    <el-row :gutter="20" class="overview-section">
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40" color="#409eff"><CreditCard /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ cardList.length }}</div>
              <div class="stat-label">银行卡数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40" color="#67c23a"><Wallet /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ totalBalance.toLocaleString() }}</div>
              <div class="stat-label">总资产</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40" color="#e6a23c"><DocumentCopy /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ recentTrades.length }}</div>
              <div class="stat-label">近期交易</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 银行卡列表 -->
    <div class="cards-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>我的银行卡</span>
            <el-button type="text" @click="$router.push('/user/cards')">查看全部</el-button>
          </div>
        </template>
        <div class="cards-list">
          <div v-if="cardList.length === 0" class="empty-state">
            <el-empty description="暂无银行卡" />
          </div>
          <div v-else class="card-grid">
            <div v-for="card in cardList.slice(0, 3)" :key="card.cardid" class="bank-card">
              <div class="card-content">
                <div class="card-header-info">
                  <span class="card-type">储蓄卡</span>
                  <el-tag :type="getCardStatusType(card.isreportloss)" size="small">
                    {{ card.isreportloss === '否' ? '正常' : '已挂失' }}
                  </el-tag>
                </div>
                <div class="card-number">
                  {{ formatCardNumber(card.cardid) }}
                </div>
                <div class="card-balance">
                  <span class="balance-label">可用余额</span>
                  <span class="balance-amount">¥{{ Number(card.balance).toLocaleString() }}</span>
                </div>
                <div class="card-actions">
                  <el-button size="small" @click="quickDeposit(card)">存款</el-button>
                  <el-button size="small" @click="quickWithdraw(card)">取款</el-button>
                  <el-button size="small" @click="quickTransfer(card)">转账</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 最近交易 -->
    <div class="recent-trades-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>最近交易</span>
            <el-button type="text" @click="$router.push('/user/trades')">查看全部</el-button>
          </div>
        </template>
        <div class="trades-list">
          <div v-if="recentTrades.length === 0" class="empty-state">
            <el-empty description="暂无交易记录" />
          </div>
          <div v-else>
            <div v-for="trade in recentTrades" :key="trade.tradeid" class="trade-item">
              <div class="trade-icon">
                <el-icon :color="getTradeColor(trade.tradetype)">
                  <component :is="getTradeIcon(trade.tradetype)" />
                </el-icon>
              </div>
              <div class="trade-info">
                <div class="trade-title">{{ trade.tradetype }}</div>
                <div class="trade-desc">{{ formatCardNumber(trade.cardid) }} • {{ formatTime(trade.tradedate) }}</div>
              </div>
              <div class="trade-amount" :class="getAmountClass(trade.tradetype)">
                {{ getAmountText(trade.tradetype, trade.trademoney) }}
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 快捷操作对话框 -->
    <QuickActionDialog
      v-model:visible="quickDialogVisible"
      :action-type="quickActionType"
      :selected-card="selectedCard"
      @success="handleQuickActionSuccess"
    />
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { 
  User, 
  Money, 
  CreditCard, 
  Wallet, 
  DocumentCopy,
  Plus,
  Minus,
  Switch
} from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import QuickActionDialog from '@/components/QuickActionDialog.vue'

export default {
  name: 'UserDashboard',
  components: {
    User,
    Money,
    CreditCard,
    Wallet,
    DocumentCopy,
    Plus,
    Minus,
    Switch,
    QuickActionDialog
  },
  setup() {
    const store = useStore()
    const quickDialogVisible = ref(false)
    const quickActionType = ref('')
    const selectedCard = ref(null)

    // 用户信息
    const userInfo = computed(() => store.state.userInfo)
    
    // 数据
    const cardList = ref([])
    const recentTrades = ref([])
    const loading = ref(false)

    // 计算总余额
    const totalBalance = computed(() => {
      return cardList.value.reduce((total, card) => total + Number(card.balance || 0), 0)
    })

    // 获取用户银行卡
    const fetchUserCards = async () => {
      try {
        const response = await userApi.getUserCards()
        if (response.code === 0) {
          cardList.value = response.data || []
        }
      } catch (error) {
        console.error('获取银行卡失败:', error)
      }
    }

    // 获取最近交易记录
    const loadRecentTrades = async () => {
      try {
        // 构建查询参数 - 按照bank-front项目的格式
        const queryData = {
          tradeid: 0,
          cardid: '',
          tradetype: '',
          minMoney: 0,
          maxMoney: 0,
          remark: '',
          page: 1,
          pageSize: 5
        }
        
        // 获取最近7天的记录
        const endDate = new Date()
        const startDate = new Date()
        startDate.setDate(endDate.getDate() - 7)
        
        const begin = startDate.toISOString().split('T')[0]
        const end = endDate.toISOString().split('T')[0]
        
        console.log('Dashboard交易查询参数:', queryData, begin, end)
        
        const response = await userApi.pageTradeUser(queryData, begin, end)
        if (response && response.code === 0) {
          recentTrades.value = response.data?.records || []
        } else {
          console.error('获取最近交易记录失败:', response)
          recentTrades.value = []
        }
      } catch (error) {
        console.error('获取最近交易记录失败:', error)
        recentTrades.value = []
      }
    }

    // 格式化卡号
    const formatCardNumber = (cardNumber) => {
      if (!cardNumber) return ''
      return cardNumber.replace(/(\d{4})(?=\d)/g, '$1 ')
    }

    // 格式化时间
    const formatTime = (time) => {
      if (!time) return ''
      return new Date(time).toLocaleString()
    }

    // 获取卡片状态类型
    const getCardStatusType = (status) => {
      return status === '否' ? 'success' : 'danger'
    }

    // 获取交易图标
    const getTradeIcon = (type) => {
      switch (type) {
        case '存款': return Plus
        case '取款': return Minus
        case '转账': return Switch
        default: return DocumentCopy
      }
    }

    // 获取交易颜色
    const getTradeColor = (type) => {
      switch (type) {
        case '存款': return '#67c23a'
        case '取款': return '#f56c6c'
        case '转账': return '#409eff'
        default: return '#909399'
      }
    }

    // 获取金额样式类
    const getAmountClass = (type) => {
      switch (type) {
        case '存款': return 'amount-positive'
        case '取款': return 'amount-negative'
        case '转账': return 'amount-negative'
        default: return ''
      }
    }

    // 获取金额文本
    const getAmountText = (type, amount) => {
      const prefix = type === '存款' ? '+' : '-'
      return `${prefix}¥${Number(amount).toLocaleString()}`
    }

    // 快捷操作
    const quickDeposit = (card) => {
      selectedCard.value = card
      quickActionType.value = 'deposit'
      quickDialogVisible.value = true
    }

    const quickWithdraw = (card) => {
      selectedCard.value = card
      quickActionType.value = 'withdraw'
      quickDialogVisible.value = true
    }

    const quickTransfer = (card) => {
      selectedCard.value = card
      quickActionType.value = 'transfer'
      quickDialogVisible.value = true
    }

    // 快捷操作成功回调
    const handleQuickActionSuccess = () => {
      fetchUserCards()
      loadRecentTrades()
    }

    // 初始化数据
    onMounted(() => {
      fetchUserCards()
      loadRecentTrades()
    })

    return {
      userInfo,
      cardList,
      recentTrades,
      totalBalance,
      loading,
      quickDialogVisible,
      quickActionType,
      selectedCard,
      formatCardNumber,
      formatTime,
      getCardStatusType,
      getTradeIcon,
      getTradeColor,
      getAmountClass,
      getAmountText,
      quickDeposit,
      quickWithdraw,
      quickTransfer,
      handleQuickActionSuccess
    }
  }
}
</script>

<style lang="scss" scoped>
.user-dashboard {
  .welcome-section {
    margin-bottom: 20px;

    .welcome-card {
      .welcome-content {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .user-info {
          display: flex;
          align-items: center;
          gap: 16px;

          .user-details {
            h3 {
              margin: 0 0 8px 0;
              color: #303133;
            }
            p {
              margin: 0;
              color: #909399;
              font-size: 14px;
            }
          }
        }

        .quick-actions {
          display: flex;
          gap: 12px;
        }
      }
    }
  }

  .overview-section {
    margin-bottom: 20px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        gap: 16px;

        .stat-icon {
          flex-shrink: 0;
        }

        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 4px;
          }

          .stat-label {
            color: #909399;
            font-size: 14px;
          }
        }
      }
    }
  }

  .cards-section,
  .recent-trades-section {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 16px;

      .bank-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 12px;
        padding: 20px;
        color: white;

        .card-header-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;

          .card-type {
            font-size: 14px;
            opacity: 0.9;
          }
        }

        .card-number {
          font-size: 18px;
          font-weight: 600;
          margin-bottom: 16px;
          letter-spacing: 2px;
        }

        .card-balance {
          margin-bottom: 16px;

          .balance-label {
            display: block;
            font-size: 12px;
            opacity: 0.8;
            margin-bottom: 4px;
          }

          .balance-amount {
            font-size: 20px;
            font-weight: bold;
          }
        }

        .card-actions {
          display: flex;
          gap: 8px;

          .el-button {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;

            &:hover {
              background: rgba(255, 255, 255, 0.3);
            }
          }
        }
      }
    }

    .trades-list {
      .trade-item {
        display: flex;
        align-items: center;
        padding: 16px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .trade-icon {
          margin-right: 16px;
        }

        .trade-info {
          flex: 1;

          .trade-title {
            font-weight: 500;
            color: #303133;
            margin-bottom: 4px;
          }

          .trade-desc {
            color: #909399;
            font-size: 14px;
          }
        }

        .trade-amount {
          font-weight: 600;

          &.amount-positive {
            color: #67c23a;
          }

          &.amount-negative {
            color: #f56c6c;
          }
        }
      }
    }

    .empty-state {
      text-align: center;
      padding: 40px 0;
    }
  }
}
</style> 